package com.cyy.view.search

import cn.hutool.core.io.FileUtil
import cn.hutool.core.util.CharsetUtil
import cn.hutool.setting.Setting
import com.cyy.model.GmodelModel
import com.cyy.model.SqlHistory
import com.cyy.model.SqlViewModel
import com.cyy.util.U
import com.cyy.view.GenEvent
import com.jfinal.plugin.activerecord.Db
import javafx.scene.layout.Priority
import tornadofx.*

class SearchHisttory : View("My View") {
    val gm: GmodelModel by inject()
    val sqlvm: SqlViewModel by inject()
    val sqlList = sqlvm.sqlList
    val setting = Setting(FileUtil.touch("searchHistory.txt"), CharsetUtil.CHARSET_UTF_8, true)
    val map1 = setting.getMap("")
    override val root = vbox {
        tableview(sqlList) {
            vgrow = Priority.ALWAYS

            column("Key", SqlHistory::sqlKeyProperty)
            column("Value", SqlHistory::sqlValueProperty)
            column("DbName", SqlHistory::dbnameProperty)
            column("Table", SqlHistory::tableProperty)
            column("Kv", SqlHistory::kvProperty)
            bindSelected(sqlvm)
            contextmenu {
                item("查寻").action {
                    selectedItem?.apply { Search(sqlvm.sqlValue.value, sqlvm.kv.value) }
                }
                item("Delete").action {
                    selectedItem?.apply {
                        //                            println(selectedItem.toString())
                        val t = selectedItem.toString()
                        sqlList.remove(selectedItem)
                        setting.remove(this.sqlKey)
                        setting.entries
                        setting.store("searchHistory.txt")
                        fire(GenEvent("删除${t}成功！ "))
                    }
                }
            }
        }

        button("查寻").action {
            //                        searchSql.bind(Observab)
            Search(sqlvm.sqlValue.value, sqlvm.kv.value)
        }

    }

    init {
        map1.mapEach {
            val list = this.value.split("|")
            sqlList.add(SqlHistory(this.key, list[0], list[1], list[2], list[3]))
        }
    }

    fun Search(sql: String, kv: String) {
        val kv1 = U.str2Kv(kv)
        runAsync {
            try {
                val ret = Db.use().find(sql)
                kv1.set("ret", ret)
            } catch (e: Exception) {
                println("search failed : ${e}")
                fire(GenEvent("search failed : ${e}"))
            }
        } ui { success ->
            gm.tplStringOut.value = gm.engine.value.getTemplate(sqlvm.wbtmpl.value).renderToString(kv1)
        }
    }
}
